package com.example.messagedigest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {

    private String pw = "arashi12345";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //button的点击事件，进行运算
    public void messageDigest(View view) {
        switch (view.getId()){
            case R.id.md5://32位
                String md5 = messageDigest("MD5", pw);
                Log.d("1608","经过MD5运算后的结果:"+md5);
                break;
            case R.id.sha1://40位
                String sha = messageDigest("SHA-1", pw);
                Log.d("1608","经过AHA-1运算后的结果:"+sha);
                break;
        }
    }

    //运算方法
    private String messageDigest(String type, String data) {
        try {
            //1.创建消息摘要的对象
            MessageDigest messageDigest = MessageDigest.getInstance(type);
            //2.调用对象的方法，进行运算
            //将要运算的数据加载给MessageDigest
            messageDigest.update(data.getBytes());
            byte[] digest = messageDigest.digest();
            //3.将字节数组转换成该样式
            //规律：0到9，a到f：十六进制表示数据
            //3.1打印运算后的数据
            Log.d("1608","hash值的字节数组长度" + digest);

            for (int i = 0; i < digest.length; i++) {
//                Log.d("1608",""+digest[i]);
                Log.d("1608","二进制："+ Integer.toBinaryString(digest[i]));
            }

            //二进制
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < digest.length; i++) {
                //0xFF = 二进制：11111111
                int mun = digest[i] & 0xFF;
                if (mun<= 0xF){
                    builder.append(0);
                }
                String result = Integer.toHexString(mun);
                builder.append(result);
            }
            //运算后的数据进行返回
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
